package trade.axht.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import trade.axht.util.QiniuUtils;

import com.baidu.ueditor.ActionEnter;

@Controller
@RequestMapping("/qiniu")
public class UploadController {
	@RequestMapping(value = "/config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        String rootPath = request.getSession()
                .getServletContext().getRealPath("/");

        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 多文件上传支持 
     * @param upfile
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "uploadfile")
    public Map uploadFile(@RequestParam(value = "upfile", required = false) MultipartFile[] upfile) throws Exception{
        Map<String,String> map = new HashMap<String, String>();
        if (upfile != null && upfile.length > 0){
            //循环获取file数组中得文件
            for(int i = 0;i<upfile.length;i++){
                MultipartFile file = upfile[i];
                String fileName = file.getOriginalFilename();
                byte[] fileByte = file.getBytes();
                //返回对象
                System.out.println("上传文件"+fileName);
                try {
                    new QiniuUtils().uploadFile(fileByte,fileName);
                    map.put("url",fileName);
                    map.put("name",fileName);
                    map.put("state","SUCCESS");
                }catch (Exception e){
                    e.printStackTrace();
                    map.put("state","上传失败!");
                }
            }
        }
        return map;
    }
}
